﻿using System;
using System.Web;
using MS.InformationManagement.BLL.RecordCenter;
using bll = MS.InformationManagement.BLL.ExpedienteViewer;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.WP.Layouts.MS.InformationManagement.WP
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class ExportHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.QueryString.Get("action");
            if (string.IsNullOrEmpty(action)) { throw new Exception("Se esperaba un parametro en la url"); }
            switch (action.ToLower())
            {
                case "trdhistoricdata":
                    ExportTRDHistoricalData();
                    break;
                case "trdconfigdata":
                    ExportTRDConfigData();
                    break;
                case "trdpendigconfigdata":
                    ExportTRDPendingItems();
                    break;
                case "folderbyvolume":
                    ExportFolderByVolume();
                    break;
                case "exportfolder":
                    ExportFolder();
                    break;
                default:
                    throw new Exception("Operación no soportada");
                    break;
            }
        }

        #region [TRD Export Members]

        private void ExportTRDHistoricalData()
        {
            int backdropId = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("bID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("bID"));
            int backdropChildId = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("bcID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("bcID"));
            int sectionID = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("sID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("sID"));
            int subSectionID = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("sbID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("sbID"));

            string trdHistoricalFileContent = CsvExportHelper.ExportToCSV(
                TRDBLL.GetHistoricItemsExportData(new FondosFondo { Id = backdropId }, new FondosFondo { Id = backdropChildId }, new SeccionesSeccion { Id = sectionID }, new SeccionesSeccion { Id = subSectionID }),
                new string[] { "Fecha", "Amodministrador", "Serie", "Subserie", "Operacion Realizada", "Observaciones" }, ';');

            ExportToCsv("HistoricoTRD", trdHistoricalFileContent);
        }

        private void ExportTRDConfigData()
        {
            int backdropId = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("bID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("bID"));
            int backdropChildId = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("bcID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("bcID"));
            int sectionID = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("sID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("sID"));
            int subSectionID = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("sbID")) ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("sbID"));

            string trditemsFileContent = CsvExportHelper.ExportToCSV(
                TRDBLL.GetTRDConfigItemsExportData(new FondosFondo { Id = backdropId }, new FondosFondo { Id = backdropChildId }, new SeccionesSeccion { Id = sectionID }, new SeccionesSeccion { Id = subSectionID }),
                new string[] { "D", "S", "SB", "Serie", "Subserie", "Tipos Documentales", "AG", "AC", "C", "MT", "S", "E", "Observaciones" }, ';');

            ExportToCsv("TRD", trditemsFileContent);
        }

        private void ExportTRDPendingItems()
        {
            string pendingsectionsFileContent = CsvExportHelper.ExportToCSV(TRDBLL.GetPendingSectionsExportData(),
                new string[] { "Codigo", "Seccion", "Subseccion", "Usuario Encargado Correspondencia" }, ';');
            ExportToCsv("SeccionesPendientes", pendingsectionsFileContent);
        }
 
        #endregion

        #region [Expedientes]

        private void ExportFolderByVolume()
        {
            bll.ExpedienteViewer objBLL = new bll.ExpedienteViewer();
            string idExp = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("expID")) ? string.Empty : HttpContext.Current.Request.QueryString.Get("expID");
            string idTomo = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("volID")) ? string.Empty : HttpContext.Current.Request.QueryString.Get("volID");
            string volFileCOntent = CsvExportHelper.ExportToCSV(objBLL.GetRadicadosByExpedienteAndVolumeTable(idExp, idTomo),
                new string[] { "Radicado", "Fecha Creacion", "Remitente / Destinatario", "Tipo Documental", "Tipo Radicado", "Usuario Asignado" }, ';');
            ExportToCsv("RadicadosTomo" + idTomo, volFileCOntent);
        }

        private void ExportFolder()
        {
            bll.ExpedienteViewer objBLL = new bll.ExpedienteViewer();
            string idExp = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString.Get("expID")) ? string.Empty : HttpContext.Current.Request.QueryString.Get("expID");
            string volFileCOntent = CsvExportHelper.ExportToCSV(objBLL.GetRadicadosByExpedienteTable(idExp),
                new string[] { "Radicado", "Fecha Creacion", "Remitente / Destinatario", "Tipo Documental", "Tipo Radicado", "Usuario Asignado" }, ';');
            ExportToCsv("RadicadosExpediente" + idExp, volFileCOntent);
        }

        #endregion

        private void ExportToCsv(string fileName, string fileContent)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ContentType = "application/csv";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv", fileName));
            HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            HttpContext.Current.Response.Write(fileContent);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}